package com.example.yuan0605.test;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.yml.R;

public class Login2Activity extends AppCompatActivity implements View.OnClickListener {
    private EditText etName;
    private EditText etPw;
    private EditText etSex;
    private Button dl;
    private Button zc;
    private Users db;
    SharedPreferences sp;
    boolean flag; //第一次安装的状态

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_2);
        init();
    }

    public void init() {
        etName = findViewById(R.id.et_name);
        etPw = findViewById(R.id.et_pw);
        etSex = findViewById(R.id.et_sex);
        dl = findViewById(R.id.dl);
        zc = findViewById(R.id.zc);
        db = new Users(this, 1);
        dl.setOnClickListener(this);
        zc.setOnClickListener(this);
        sp = getSharedPreferences("zt", Context.MODE_PRIVATE);
        flag = sp.getBoolean("flag", false);
        //把性别显示出来
        if (flag) {
            db = new Users(this, 2);
            etSex.setVisibility(View.VISIBLE);
        }
        SharedPreferences.Editor edit = sp.edit();
        edit.putBoolean("flag", true);
        edit.commit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dl:
                Intent intent = new Intent(Login2Activity.this, Main2Activity.class);
                intent.putExtra("issex", flag);
                startActivity(intent);
                break;
            case R.id.zc:
                String name = etName.getText().toString().trim();
                String pw = etPw.getText().toString().trim();
                String sex = etSex.getText().toString().trim();
                if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pw)) {
                    Toast.makeText(this, "用户名密码不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    SQLiteDatabase zcdb = db.getWritableDatabase();
                    ContentValues values = new ContentValues();
                    values.put("username", name);
                    values.put("password", pw);
                    //插入性别的值
                    if (flag) {
                        values.put("sex", sex);
                    }
                    zcdb.insert("user", null, values);
                    zcdb.close();
                    Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
